<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { RoleModel } from '#/api/system/models';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Button, message, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRoleApi, getRolePagedListApi } from '#/api/system/role';
import { $t } from '#/locales';

import { useColumns } from './data';
import RoleFormModal from './modules/form.vue';
import RoleMenuFormDrawer from './modules/role-menu.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: RoleFormModal,
  destroyOnClose: true,
});

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: RoleMenuFormDrawer,
  destroyOnClose: true,
});

/**
 * 创建角色
 */
function onCreate() {
  formModalApi.setData(null).open();
}

/**
 * 编辑角色
 * @param row
 */
function onEdit(row: RoleModel) {
  formModalApi.setData(row).open();
}

/**
 * 删除角色
 * @param row
 */
function onDelete(row: RoleModel) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteRoleApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.name]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 授权菜单
 * @param row
 */
function onGrant(row: RoleModel) {
  formDrawerApi.setData(row).open();
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<RoleModel>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'grant': {
      onGrant(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    stripe: true,
    pagerConfig: {},
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getRolePagedListApi({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="refreshGrid()" />
    <FormDrawer />
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="onCreate()"> 新增角色 </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
